package org.yoki.edu.bg.radius.filter.app.operator;

import org.yoki.edu.bg.radius.core.client.domain.Client;
import org.yoki.edu.bg.radius.filter.app.obs.SynObservable;
import org.yoki.edu.bg.radius.filter.app.receiver.packet.RadiusPacket;
import com.yunzhitx.cloud.common.protocol.radius.attribute.attr.RadiusMsgAttr;
import com.yunzhitx.cloud.common.protocol.radius.attribute.attr.acct.AcctStatusTypeAttr;
import com.yunzhitx.cloud.common.protocol.radius.msg.packet.RadiusMsg;
import com.yunzhitx.cloud.common.protocol.radius.msg.parser.RadiusPacketParser;

import java.net.DatagramPacket;
import java.util.List;

/**
 * @author Sky$
 * @Description: TODO
 * @date 2018/1/4$ 16:09$
 */
public class AcctPacketLogoutOperator implements SynPacketOperator {

    @Override
    public void update(SynObservable o, Object... args) {
        if (null == args && args.length <= 0) {
            return;
        }
        if (args.length < 2) {
            return;
        }
        RadiusPacket clientRadiusPacket = (RadiusPacket) args[0];
        RadiusPacket serverRadiusPacket = (RadiusPacket) args[1];
        DatagramPacket packet = clientRadiusPacket.getPacket();
        String ip = packet.getAddress().getHostAddress();
        Client client = Client.selectDetailByIpAddr(ip);
        String clientSecret = client.getSecret();
        byte[] rawBytes = new byte[packet.getLength()];
        System.arraycopy(packet.getData(), 0, rawBytes, 0, rawBytes.length);
        RadiusMsg clientMsg = RadiusPacketParser.parseReqPacket(rawBytes, clientSecret);
        List<RadiusMsgAttr> attrList = clientMsg.getAttributes() ;
        if(null != attrList){
            for (RadiusMsgAttr attr : attrList){
                if(attr.getType() == AcctStatusTypeAttr.ATTR_TYPE){
                    int status = (int) attr.getValue();
                    if(2 == status) {
                        System.out.println("--------------------------------------用户下线!!!!!");
                    }else{
                        break;
                    }
                }
            }
        }
    }

}
